'use strict';
const db = uniCloud.database();
const collection = db.collection('notes');

exports.main = async (event, context) => {
  const { action, params } = event;
  
  try {
    switch (action) {
      case 'add':
        return await addNote(params);
      case 'delete':
        return await deleteNote(params);
      case 'update':
        return await updateNote(params);
      case 'getList':
        return await getNoteList();
      case 'getDetail':
        return await getNoteDetail(params);
      default:
        return {
          code: 400,
          message: '未知操作'
        };
    }
  } catch (e) {
    return {
      code: 500,
      message: `服务端错误: ${e.message}`
    };
  }
};

// 添加笔记
async function addNote(params) {
  const res = await collection.add({
    title: params.title,
    content: params.content,
    created_at: new Date().getTime(),
    updated_at: new Date().getTime()
  });
  
  return {
    code: 200,
    message: '添加成功',
    id: res.id
  };
}

// 删除笔记
async function deleteNote(params) {
  const res = await collection.doc(params.id).remove();
  
  if (res.deleted === 1) {
    return {
      code: 200,
      message: '删除成功'
    };
  }
  
  return {
    code: 404,
    message: '未找到该笔记'
  };
}

// 更新笔记
async function updateNote(params) {
  const res = await collection.doc(params.id).update({
    title: params.title,
    content: params.content,
    updated_at: new Date().getTime()
  });
  
  if (res.updated === 1) {
    return {
      code: 200,
      message: '更新成功'
    };
  }
  
  return {
    code: 404,
    message: '未找到该笔记'
  };
}

// 获取笔记列表
async function getNoteList() {
  const res = await collection.orderBy('updated_at', 'desc').get();
  return {
    code: 200,
    data: res.data
  };
}

// 获取笔记详情
async function getNoteDetail(params) {
  const res = await collection.doc(params.id).get();
  
  if (res.data.length > 0) {
    return {
      code: 200,
      data: res.data[0]
    };
  }
  
  return {
    code: 404,
    message: '未找到该笔记'
  };
}